package com.hnyfkj.jyindustry.common.exception;

import com.hnyfkj.jyindustry.common.dto.RespDto;
import org.apache.shiro.authc.IncorrectCredentialsException;
import org.apache.shiro.authc.LockedAccountException;
import org.apache.shiro.authz.AuthorizationException;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.dao.DuplicateKeyException;
import org.springframework.http.converter.HttpMessageNotReadableException;
import org.springframework.web.HttpRequestMethodNotSupportedException;
import org.springframework.web.bind.annotation.ExceptionHandler;
import org.springframework.web.bind.annotation.RestControllerAdvice;

/**
 * @program: jyindustry
 * @description:异常处理类，返回json格式内容
 * @author: zl
 * @create: 2020-07-09 18:05
 **/
@RestControllerAdvice
public class HnyfkjBusinessExceptionHandler {

	private final Logger logger = LoggerFactory.getLogger(getClass());

	/**
	 * 自定义异常
	 */
	@ExceptionHandler(HnyfkjBusinessException.class)
	public RespDto handleBusinessException(final HnyfkjBusinessException e) {
		logger.info("业务异常:" + e.getMessage());
		return new RespDto(e.getCode(), e.getMessage(), null);
	}

	@ExceptionHandler(DuplicateKeyException.class)
	public RespDto handleDuplicateKeyException(final DuplicateKeyException e) {
		logger.info(e.getMessage());
		return new RespDto(500, "数据库中已存在该记录", null);
	}

	@ExceptionHandler(AuthorizationException.class)
	public RespDto handleAuthorizationException(final AuthorizationException e) {
		logger.info(e.getMessage());
		return new RespDto(403, "没有权限，请联系管理员授权", null);
	}

	@ExceptionHandler(IncorrectCredentialsException.class)
	public RespDto handleIncorrectCredentialsException(final IncorrectCredentialsException e) {
		logger.info(e.getMessage());
		return new RespDto(401, "token失效，请重新登录", null);
	}

	@ExceptionHandler(LockedAccountException.class)
	public RespDto handleLockedAccountException(final LockedAccountException e) {
		logger.info(e.getMessage());
		return new RespDto(500, "用户已被停用", null);
	}

	@ExceptionHandler(HttpMessageNotReadableException.class)
	public RespDto handleHttpMessageNotReadableException(final HttpMessageNotReadableException e) {
		logger.info(e.getMessage());
		return new RespDto(400, "传入参数异常，解析失败", null);
	}

	@ExceptionHandler(HttpRequestMethodNotSupportedException.class)
	public RespDto httpRequestMethodNotSupportedException(final HttpRequestMethodNotSupportedException e) {
		logger.info(e.getMessage());
		return new RespDto(400, "HttpMethod不支持", null);
	}

	@ExceptionHandler(Exception.class)
	public RespDto handleException(final Exception e) {
		logger.error(e.getMessage(), e);
		return new RespDto(500, "服务异常", null);
	}

}
